package controller;

import java.io.IOException;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.util.Log;
import app.cloudstringers.Home;

import com.google.android.gms.gcm.GoogleCloudMessaging;

public class RegisterGCMClientAsync extends AsyncTask<Void, Void, String> {

	/**
	 * String section
	 */
	private String SENDER_ID;
	private String regid;
	
	private String TAG = RegisterGCMClientAsync.class.getSimpleName(); 

	/**
	 * The others section
	 */
	private GoogleCloudMessaging gcm;
	private Context context;
	
	/**
	 * 
	 * @param context
	 * @param gcm
	 * @param SENDER_ID
	 * @param regid
	 */
	public RegisterGCMClientAsync(Context context, GoogleCloudMessaging gcm,
			String SENDER_ID, String regid) {
		this.context = context;
		this.gcm = gcm;
		this.SENDER_ID = SENDER_ID;
		this.regid = regid;
	}
	
	/**
	 * Registers the application with GCM servers asynchronously.
	 * <p>
	 * Stores the registration ID and app versionCode in the application's
	 * shared preferences.
	 */
	@Override
	protected String doInBackground(Void... params) {
		String msg = "";
        try {
            if (gcm == null) {
                gcm = GoogleCloudMessaging.getInstance(context);
            }
            regid = gcm.register(SENDER_ID);
            msg = "Device registered, registration ID=" + regid;

            // You should send the registration ID to your server over HTTP,
            // so it can use GCM/HTTP or CCS to send messages to your app.
            // The request to your server should be authenticated if your app
            // is using accounts.
            sendRegistrationIdToBackend();

            // For this demo: we don't need to send it because the device
            // will send upstream messages to a server that echo back the
            // message using the 'from' address in the message.

            // Persist the regID - no need to register again.
            storeRegistrationId(context, regid);
        } catch (IOException ex) {
            msg = "Error :" + ex.getMessage();
            // If there is an error, don't just keep trying to register.
            // Require the user to click a button again, or perform
            // exponential back-off.
        }
        return msg;
	}

	@Override
	protected void onPostExecute(String result) {
		super.onPostExecute(result);
		
		Log.i(TAG, "Register new ID : " + result);
	}
	
	/**
	 * Sends the registration ID to your server over HTTP, so it can use GCM/HTTP
	 * or CCS to send messages to your app. Not needed for this demo since the
	 * device sends upstream messages to a server that echoes back the message
	 * using the 'from' address in the message.
	 */
	private void sendRegistrationIdToBackend() {
	    // Your implementation here.
	}
	
	/**
	 * Stores the registration ID and app versionCode in the application's
	 * {@code SharedPreferences}.
	 *
	 * @param context application's context.
	 * @param regId registration ID
	 */
	private void storeRegistrationId(Context context, String regId) {
	    final SharedPreferences prefs = getGCMPreferences(context);
	    int appVersion = getAppVersion(context);
	    
	    Log.i(TAG, "Saving regId on app version " + appVersion);
	    
	    SharedPreferences.Editor editor = prefs.edit();
	    editor.putString(define.Login.PROPERTY_REG_ID, regId);
	    editor.putInt(define.Login.PROPERTY_APP_VERSION, appVersion);
	    editor.commit();
	}
	
	/**
	 * @return Application's {@code SharedPreferences}.
	 */
	private SharedPreferences getGCMPreferences(Context context) {
	    // This sample app persists the registration ID in shared preferences, but
	    // how you store the regID in your app is up to you.
	    return context.getSharedPreferences(Home.class.getSimpleName(),
	            Context.MODE_PRIVATE);
	}
	
	/**
	 * @return Application's version code from the {@code PackageManager}.
	 */
	private static int getAppVersion(Context context) {
	    try {
	        PackageInfo packageInfo = context.getPackageManager()
	                .getPackageInfo(context.getPackageName(), 0);
	        return packageInfo.versionCode;
	    } catch (NameNotFoundException e) {
	        // should never happen
	        throw new RuntimeException("Could not get package name: " + e);
	    }
	}
}
